import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Blog, BlogQuery } from '@/types'
import request from '@/utils/request'

export const useBlogStore = defineStore('blog', () => {
  const blogs = ref<Blog[]>([])
  const currentBlog = ref<Blog | null>(null)
  const total = ref(0)
  const loading = ref(false)

  const fetchBlogs = async (query: BlogQuery) => {
    loading.value = true
    try {
      const res = await request.get('/blogs', { params: query })
      blogs.value = res.items
      total.value = res.total
    } finally {
      loading.value = false
    }
  }

  const fetchBlogDetail = async (id: number) => {
    loading.value = true
    try {
      const res = await request.get(`/blogs/${id}`)
      currentBlog.value = res
    } finally {
      loading.value = false
    }
  }

  const createBlog = async (blog: Partial<Blog>) => {
    const res = await request.post('/blogs', blog)
    return res
  }

  const updateBlog = async (id: number, blog: Partial<Blog>) => {
    const res = await request.put(`/blogs/${id}`, blog)
    return res
  }

  const deleteBlog = async (id: number) => {
    await request.delete(`/blogs/${id}`)
  }

  return {
    blogs,
    currentBlog,
    total,
    loading,
    fetchBlogs,
    fetchBlogDetail,
    createBlog,
    updateBlog,
    deleteBlog
  }
}) 